package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.entity.PageResult;
import com.itheima.entity.Result;
import com.itheima.entity.StatusCode;
import com.itheima.mapper.GoodsMapper;
import com.itheima.pojo.Goods;
import com.itheima.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * Create By Awen on 2021/9/28
 *
 * @author Awen
 */
@Service
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements GoodsService {

    @Autowired
    private GoodsMapper goodsMapper;

    @Override
    public Result findPage(Integer curPage, Integer size) {
        IPage<Goods> goodsPage = new Page<>(curPage,size);
        goodsMapper.selectPage(goodsPage, null);
        List<Goods> goods = goodsPage.getRecords();
        if (goods.size() == 0){
            return Result.builder().flag(false).message("无数据").build();
        }
        PageResult<Goods> pageResult = new PageResult<>();
        pageResult.setTotal(goodsPage.getTotal());
        pageResult.setRows(goodsPage.getRecords());
        return Result.builder().flag(true).data(pageResult).code(StatusCode.OK).build();
    }

    @Override
    public Result findById(Integer id) {
        Goods goods = goodsMapper.selectById(id);
        if (goods == null){

        }
        return Result.builder().flag(true).data(goods).code(StatusCode.OK).build();
    }

    @Override
    public Result add(Goods goods) {
        goods.setId(null);
        goods.setIsMarketable("0");//默认未上架
        goods.setStatus("0");//默认未审核
        goods.setCreatetime(new Date());
        goods.setUpdatetime(new Date());
        goods.setSaleNum(0);
        goods.setCommentNum(0);
        int i = goodsMapper.insert(goods);
        if (i>0){
            return Result.builder().flag(true).message("添加成功").code(StatusCode.OK).build();
        }
        return Result.builder().flag(false).message("添加错误").code(StatusCode.ERROR).build();

    }

    @Override
    public Result deleteById(Integer id) {
        int i = goodsMapper.deleteById(id);
        if (i>0){
            return Result.builder().flag(true).message("删除成功").code(StatusCode.OK).build();
        }
        return Result.builder().flag(false).message("删除错误").code(StatusCode.ERROR).build();
    }


}
